﻿using Common.Service;
using Core.Domain.Model;
using NSBus.Dto.Commands;
using NServiceBus;
using Sanelib.Common.Helpers;
using Sanelib.DataOperation;

namespace NSBus.Server.CommandHandlers
{
    public class PasswordRecoveryTokenHandler : MessageHandler<PasswordRecoveryTokenCommand>
    {
        private readonly IRepository<Member> _memberRepository;
        private readonly ICryptographer _cryptographer;
        private readonly IRepository<Templete> _templeteRepository;
        public IBus Bus { get; set; }

        public PasswordRecoveryTokenHandler(IRepository<Member> memberRepository, ICryptographer cryptographer, IUnitOfWork unitOfWork, IRepository<Templete> templeteRepository) : base(unitOfWork)
        {
            _memberRepository = memberRepository;
            _cryptographer = cryptographer;
            _templeteRepository = templeteRepository;
        }

        public override void HandleMessage(PasswordRecoveryTokenCommand message)
        {
            var member = _memberRepository.GetById(message.UserId);

            var token = GetToken();

            var messageBody = _templeteRepository.GetByKey(Property.Of<Templete>(x => x.Name), "Member Registration").Value;

            member.PasswordRetrievalToken = _cryptographer.ComputeHash(token);
            member.PasswordRetrievalTokenExpirationDate = SystemTime.Now().AddDays(1);

            _memberRepository.Update(member);

            Bus.SendLocal<SendEmailCommand>(m =>
            {
                m.To = member.Email;
                m.Subject = "Sanelib Password Recovery Instructions";
                m.MessageBody = string.Format(messageBody, message.Url, token);
            });
        }

        /// <summary>
        /// Token is a salt of just 10 chars of length.
        /// </summary>
        /// <returns></returns>
        private string GetToken()
        {
            return _cryptographer.CreateSalt().Substring(0, 10);
        }
    }
}
